package com.sbj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.operator.Equal;
import cn.zhxu.bs.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbj.dto.req.CarReq;
import com.sbj.dto.res.CarRes;
import com.sbj.entity.Car;
import com.sbj.mapper.CarMapper;
import com.sbj.service.CarService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author summer
 * @version 1.0
 * @date 2024/9/10 09:39
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService {


    @Override
    public Long carNum() {
        LambdaQueryWrapper<Car> eq = Wrappers.lambdaQuery(Car.class).eq(Car::getMemberId, StpUtil.getLoginIdAsInt());
        return this.count(eq);
    }

    @Override
    public void saveCar(CarReq carReq) {
        Car car = Convert.convert(Car.class, carReq);
        car.setMemberId(StpUtil.getLoginIdAsInt());
        if(ObjectUtil.isEmpty(car.getId())){
            LambdaQueryWrapper<Car> eq = Wrappers.lambdaQuery(Car.class).eq(Car::getMemberId, StpUtil.getLoginIdAsInt()).eq(Car::getGoodsId,carReq.getGoodsId());
            Car one = this.getOne(eq);
            if(ObjectUtil.isNotEmpty(one)){
                one.setGoodNum(one.getGoodNum()+1);
                this.updateById(one);
            }else{
                this.save(car);
            }
        }else{
            this.updateById(car);
        }
    }

    private final BeanSearcher beanSearcher;

    @Override
    public List<CarRes> lists() {
        Map<String, Object> build = MapUtils.builder().field(CarRes::getMemberId, StpUtil.getLoginIdAsInt()).op(Equal.class).build();
        return beanSearcher.searchList(CarRes.class, build);
    }

    @Override
    public void carChecked(List<CarReq> carReqs) {
        LambdaQueryWrapper<Car> eq = Wrappers.lambdaQuery(Car.class).eq(Car::getMemberId, StpUtil.getLoginIdAsInt());
        Car car=new Car();
        car.setChecked(false);
        this.update(car, eq);
        List<Car> cars = ListUtil.list(true);
        carReqs.forEach(carReq -> {
            Car car1=new Car();
            car1.setId(carReq.getId());
            car1.setGoodNum(carReq.getGoodsNum());
            car1.setChecked(true);
            cars.add(car1);
        });
        this.updateBatchById(cars);
    }
}
